package com.kami.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kami.dao.SysTokenMapper;
import com.kami.entity.SysToken;
import com.kami.entity.SysTokenExample;
import com.kami.service.SysTokenService;

@Service
public class SysTokenServiceImpl implements SysTokenService{
	
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	
	@Autowired
	private SysTokenMapper sysTokenMapper;

	@Override
	public SysToken queryToken(String token) {
		SysTokenExample tokenExample = new SysTokenExample();
		tokenExample.createCriteria().andTokenEqualTo(token);
		List<SysToken> list = sysTokenMapper.selectByExample(tokenExample);
		return list.size() > 0 ? list.get(0) : null;
	}

	@Override
	public SysToken createToken(Long id) {
		String token = UUID.randomUUID().toString();
		Date now = new Date();
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
		SysToken sysToken = queryByUserId(id);
		if (sysToken == null) {
			sysToken = new SysToken();
			sysToken.setUserId(id);
			sysToken.setToken(token);
			sysToken.setUpdateTime(now);
			sysToken.setExpireTime(expireTime);
			save(sysToken);
		}else{
			sysToken.setToken(token);
			sysToken.setUpdateTime(now);
			sysToken.setExpireTime(expireTime);
			update(sysToken);
		}
		return sysToken;
	}

	@Override
	public SysToken queryByUserId(Long id) {
		return sysTokenMapper.selectByPrimaryKey(id);
	}

	@Override
	public void save(SysToken token) {
		sysTokenMapper.insertSelective(token);
	}

	@Override
	public void update(SysToken token) {
		sysTokenMapper.updateByPrimaryKeySelective(token);
	}
	
	

}
